<script setup lang="ts">
import { LoginData } from "@/api/auth/types";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
const userStore = useUserStore();
const { rsaPublicKey } = storeToRefs(userStore);
import {saPublicData} from '@/utils/rsa'

import type { FormInstance } from "element-plus";
import { getCaptchaApi } from "@/api/auth";
import router from "@/router";
const ruleFormRef = ref<FormInstance>();

const loginData = reactive<LoginData>({
  username: "zhangsan",
  password: "123456",
});
import { useI18n } from "vue-i18n";
import { useAppStore } from "@/store/modules/app";
const appStore = useAppStore();
const { t } = useI18n();
const loginRules = computed(() => {
  const prefix = appStore.language === "en" ? "Please enter " : "请输入";
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: `${prefix}${t("login.username")}`,
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        validator: (_rule: any, value: any, callback: any) => {
          if (value.length < 6) {
            callback(new Error("The password can not be less than 6 digits"));
          } else {
            callback();
          }
        },
        message: `${prefix}${t("login.password")}`,
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: `${prefix}${t("login.captchaCode")}`,
      },
    ],
  };
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
			loading.value = true;
			const password = loginData.password
			loginData.password = <string>saPublicData(loginData.password,rsaPublicKey.value)
      userStore
				.login(loginData).then(() => {
					router.push('/index')
				})
        .catch(() => {
          // 验证失败，重新生成验证码
					getCaptcha();
        })
        .finally(() => {
					loading.value = false;
					loginData.password = password
        });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const loading = ref(false); // 按钮loading
const captchaBase64 = ref(); // 验证码图片Base64字符串
const getCaptcha = async () => {
  const res = await getCaptchaApi();
  loginData.captchaKey = res.data.captchaKey;
  captchaBase64.value = res.data.captchaBase64;
};
onMounted(() => {
	getCaptcha();
	userStore.getRsaPublicKey();
});
</script>

<template>
  <div class="login h-100vh">
    <div class="w-100">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
          <div class="text-center">
            <span>登录系统</span>
          </div>
        </template>
        <!-- card body -->
        <el-form
          ref="ruleFormRef"
          :model="loginData"
          status-icon
          :rules="loginRules"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginData.username"
              :placeholder="$t('login.username')"
            >
              <template #prefix>
                <div class="p-1">
                  <svg-icon icon-class="user" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginData.password"
              type="password"
              show-password
              autocomplete="off"
              :placeholder="$t('login.password')"
            >
              <template #prefix>
                <div class="p-1">
                  <svg-icon icon-class="password" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captchaCode">
            <el-input
              v-model="loginData.captchaCode"
              :placeholder="$t('login.captchaCode')"
            >
              <template #prefix>
                <div class="p-1">
                  <svg-icon icon-class="captcha" />
                </div>
              </template>
              <template #suffix>
                <el-image
                  :src="captchaBase64"
                  @click="getCaptcha"
                  class="w-[120px] h-[48px] cursor-pointer"
                >
                  <template #error>
                    <div class="image-slot">
                      <i-ep-picture />
                    </div>
                  </template>
                </el-image>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="loading"
              class="w-full"
              type="primary"
              @click="submitForm(ruleFormRef)"
              >登录</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button class="w-full" @click="resetForm(ruleFormRef)"
              >注册</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 
    <LangSelect></LangSelect>
    login{{ rsaPublicKey }}
    <span>{{ $t("login.username") }}</span> -->
  </div>
</template>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
